<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

//活动控制器
class ActiveController extends Controller
{

    public function index()
    {
        //活动起始时间
        $active_start_time = getenv('activestarttime');
        $active_end_time   = getenv('activeendtime');
        $activelist        = ActiveController::getWeek($active_start_time,$active_end_time);
        $ingindex          = 0;
        foreach ($activelist as $key=>$activeval){
            $now_time         = time();
            $week_start_time  = strtotime($activeval['start_time']);
            $week_end_time    = strtotime($activeval['end_time'])+86399;
          
            if(($week_start_time < $now_time) && ($week_end_time > $now_time)){
                //进行中
                $ingindex = $ingindex+$key;
                $activelist[$key]['active_status']  =  1;
            }elseif($week_end_time < $now_time){
                //已结束
                $activelist[$key]['active_status']  =  2;
            }else{
                //未开始
                $activelist[$key]['active_status']  =  3;
            }
            $activelist[$key]['weekinfo'] = DB::table('waihui_active_ranking as k')
                                                ->join('waihui_member as m','k.userid','m.id')
                                                ->select('m.photo','m.id','m.username','k.ranking','k.week_profit','k.bonus')
                                                ->whereBetween('k.week_time', [$week_start_time, $week_end_time])
                                                ->orderBy('k.ranking')->limit(3)->get()->toArray();
        }
//        dd($activelist);
        // 本周已参与人次
        $start_time  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上6:00:00
        $end_time    = strtotime(date("Y-m-d H:i:s",mktime(5,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00

        $end_timea   = strtotime(date("Y-m-d H:i:s",mktime(12,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
        $num = DB::table('waihui_order')
               ->select(DB::raw('count(distinct(tel)) as num')) 
               ->where([['isstop','=',0],['end_time','>=',$start_time],['end_time','<=',$end_timea],['ispersonal','=',0]])
               ->pluck('num');

        $allnum = $num[0] ? $num[0]+100 : 100;
        if(isMobile()){
            return view('mobile.active', compact('allnum','start_time','end_time','activelist','ingindex'));
        }else{
            return view('active.active', compact('allnum','start_time','end_time','activelist','ingindex'));
        }
    }
    //周榜单
    public function rankingList(Request $request){
        $start_time = strtotime(trim($request->start_time));
        $end_time   = strtotime(trim($request->end_time));
        $list       = DB::table('waihui_active_ranking as k')
                        ->join('waihui_member as m','k.userid','m.id')
                        ->select('m.photo','m.id','m.username','k.ranking','k.week_profit','k.bonus','k.status','k.desc','k.actual_bonus','k.allpoint')
                        ->whereBetween('k.week_time', [$start_time, $end_time+86399])
                        ->orderBy('k.ranking')->limit(10)->get()->toArray();
        return json_encode($list);
    }
    //获取两个时间差的周情况
    public  static function getWeek($startdate,$enddate)
    {
        //参数不能为空
        if(!empty($startdate) && !empty($enddate)){

            //先把两个日期转为时间戳
            $startdate = strtotime($startdate);
            $enddate   = strtotime($enddate);
            //开始日期不能大于结束日期
            if($startdate <= $enddate){
              
                $end_date =  strtotime("next monday",$enddate);
                if(date("w",$startdate)==1){
                    $start_date=$startdate;
                }else{
                    $start_date=strtotime("last monday",$startdate);
                }
                //计算时间差多少周
                $countweek=($end_date-$start_date)/(7*24*3600);
                for($i=0;$i<$countweek;$i++){
                    $sd=date("Y-m-d",$start_date);
                    $ed=strtotime("+ 6 days",$start_date);
                    $eed=date("Y-m-d",$ed);
                    $arr[]=array('start_time'=>$sd,'end_time'=>$eed);
                    $start_date=strtotime("+ 1 day",$ed);
                }
                return $arr;
            }
        }
    }
    //比赛排名
    public function gameRanking(Request $request){
        $pagesize       = 10;
        $typeform       = intval(trim($request->typeform)); // 默认：iframe  1:ajax
        $searchname     = trim($request->searchname);
        $searchname     = $searchname?$searchname:"";
        $pagetype       = trim($request->type);
        $page           = intval(trim($request->page)) ? intval(trim($request->page)) :1;
        if($pagetype == 0 && $page == 1){
            $offset = 0;
        }else if($pagetype == 1){
            $offset = ($page-1)*$pagesize;
        }else{
            $page   = $page-1;
            $offset = ($page-1)*$pagesize;
        }
        $page           = $page;

        $weekstarttime  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上6:00:00
        $weekendtime    = strtotime(date("Y-m-d H:i:s",mktime(12,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00

        $where['o.isstop']     = 0; //已平仓
        $where['o.ispersonal'] = 0; //网站下单的
        $countarr       =  DB::table('waihui_member as m')
                                ->leftJoin('waihui_order as o','m.tel','o.tel')
                                ->select('m.id')
                                ->where($where)
                                ->where('m.username', 'like' , "%$searchname%")
                                ->whereBetween('o.end_time', [$weekstarttime,$weekendtime])
                                ->groupBy('m.id')
                                ->get()->toArray();
        $allnum  = count($countarr);
        $allpage = ceil($allnum/$pagesize);
        if($searchname){
            $dataarr = DB::table('waihui_member as m')
                            ->leftJoin('waihui_order as o', 'm.tel', 'o.tel')
                            ->select('m.id', 'm.tel', 'm.username', 'm.authstatus', 'm.photo', DB::raw('(SUM(o.final_point)+COUNT(o.id)*5) as week_final_point'), DB::raw('count(o.tel) as ordernum'), DB::raw("((SUM(o.final_point)+COUNT(o.id)*5)/count(o.tel)) AS single_final_point"), DB::raw("(count(case when o.trade_status='1' then 1 end) / count(o.tel))*100 AS winrate"))
                            ->where($where)
                            ->whereBetween('o.end_time', [$weekstarttime, $weekendtime])
                            ->orderBy('week_final_point', 'desc')
                            ->orderBy('single_final_point', 'desc')
                            ->groupBy('m.id')
                            ->get()->toArray();
            foreach ($dataarr as $key=>$val){
                if($val->username == $searchname){
                    $dataarr[$key] = $val;
                }else{
                    unset($dataarr[$key]);
                }
            }
        }else {
            $dataarr = DB::table('waihui_member as m')
                            ->leftJoin('waihui_order as o', 'm.tel', 'o.tel')
                            ->select('m.id', 'm.tel', 'm.username', 'm.authstatus', 'm.photo', DB::raw('(SUM(o.final_point)+COUNT(o.id)*5) as week_final_point'), DB::raw('count(o.tel) as ordernum'), DB::raw("((SUM(o.final_point)+COUNT(o.id)*5)/count(o.tel)) AS single_final_point"), DB::raw("(count(case when o.trade_status='1' then 1 end) / count(o.tel))*100 AS winrate"))
                            ->where($where)
                            ->whereBetween('o.end_time', [$weekstarttime, $weekendtime])
                            ->orderBy('week_final_point', 'desc')
                            ->orderBy('single_final_point', 'desc')
                            ->groupBy('m.id')
                            ->offset($offset)
                            ->limit($pagesize)
                            ->get();
        }
        foreach ($dataarr as $key=>$val){
            $total_point_data = DB::table('waihui_order')->select(DB::raw('(SUM(final_point)+COUNT(id)*5) as total_final_point'))->where(array('isstop'=>0,'ispersonal'=>0,'tel'=>$val->tel))->get()->toArray();
            $dataarr[$key]->total_final_point = $total_point_data?$total_point_data[0]->total_final_point:0;
        }
        if($typeform == 1){
            echo json_encode(array('dataarr'=>$dataarr,'page'=>$page,'allnum'=>$allnum,'allpage'=>$allpage,'searchname'=>$searchname));
        }else{
            return view('active.gameranking',compact('dataarr','page','allnum','allpage','searchname'));
        }
    }
    //比赛排名,点击查看个人详细策略情况
    public function showRankingInfo(Request $request){
        $userid = trim($request->userid);
        $tel    = DB::table('waihui_member')->where(array('id'=>$userid))->value('tel');
        if($tel){
            $start_time    = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date('w')==0?-6:1),date("Y")))); //周一早上6:00:00
            $end_time      = strtotime(date("Y-m-d H:i:s",mktime(12,0,0,date("m"),date("d")-date("w")+(date('w')==0?-1:6),date("Y")))); //周六早上5:00:00
            $trendpointobj = DB::table('waihui_order as o')
            			->join('waihui_type as t','t.name','o.typename')
                                ->select('t.chinaname','o.tradeid','o.typename','o.buy_status','o.begin_point','o.end_point','o.begin_time','o.end_time','o.final_point','o.target_profit_point','o.target_loss_point')
                                ->where([['o.tel','=',$tel],['o.ispersonal','=',0],['o.isstop','=',0],['o.end_time','>',$start_time],['o.end_time','<',$end_time]])
                                ->orderBy('o.end_time','desc')->get()->toArray();
            $timearr  = [];
            $pointarr = [];
            $point = 0;
            $trendpointobj1 = array_reverse($trendpointobj);
            foreach ($trendpointobj1 as $tkey=>$tval){
                $timearr[]  = $tval->end_time;
                $point      = $point+$tval->final_point+5;
                $pointarr[] = $point;
            }
            $timesstr   = implode(',',$timearr);
            $pointstr   = implode(',',$pointarr);
            echo json_encode(array('status'=>0,'msg'=>'数据读取成功','timesstr'=>$timesstr,'pointstr'=>$pointstr,'trendpointobj'=>$trendpointobj));
        }else{
            echo json_encode(array('status'=>1,'msg'=>'用户信息不正确'));
        }

    }
    public function help(){
        return view('active.help');
    }

    public function error(){  //判断如果是IE10以下，那么跳转
        
        return view('active.error');
    }
    
    //活动页面每周前十名入库
    public function winAward(){
        if(date('w') != 0 && date('w') != 6){
            return '今天不是周六或者周日，不能入库';
        }
        $weekTime = DB::table('waihui_active_ranking')->select('week_time')->orderby('id','desc')->value('week_time');
        if(date('Y-m-d',$weekTime) == date('Y-m-d')){
            return '这周的排行已经入过库了';
        }
        
        $where['o.isstop']     = 0; //已平仓
        $where['o.ispersonal'] = 0; //网站下单的
        
        $weekstarttime  = strtotime(date("Y-m-d H:i:s",mktime(6,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上6:00:00
        $weekendtime    = strtotime(date("Y-m-d H:i:s",mktime(12,0,0,date("m"),date("d")-date("w")+(date("w")==0?-1:6),date("Y")))); //周六早上5:00:00
        $dataarr    = DB::table('waihui_member as m')
                    ->leftJoin('waihui_order as o', 'm.tel', 'o.tel')
                    ->select('m.id', 'm.tel', 'm.username', 'm.photo', DB::raw('SUM(final_point) as week_final_point'), DB::raw('count(o.tel) as ordernum'), DB::raw("(SUM(final_point)/count(o.tel)) AS single_final_point"), DB::raw("(count(case when o.trade_status='1' then 1 end) / count(o.tel))*100 AS winrate"))
                    ->where($where)
                    ->whereBetween('o.end_time', [$weekstarttime, $weekendtime])
                    ->orderBy('week_final_point', 'desc')
                    ->orderBy('single_final_point', 'desc')
                    ->groupBy('m.id')
                    ->limit(10)
                    ->get();
        $insertData = array();
        foreach($dataarr as $k=>$v){
            //用户的总点位
            foreach ($dataarr as $key=>$val){
                $total_point_data = DB::table('waihui_order')->select(DB::raw('SUM(final_point) as total_final_point'))->where(array('isstop'=>0,'ispersonal'=>0,'tel'=>$val->tel))->get()->toArray();
                $dataarr[$key]->total_final_point = $total_point_data?$total_point_data[0]->total_final_point:0;
            }
            
            //如果总赢点位小于0，那么奖金减半
            if($k == 0){ //第一名
                $insertData[$k]['bonus'] = 2000;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 2000 : 1000;
                
            }else if($k == 1){ //第二名
                $insertData[$k]['bonus'] = 1600;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 1600 : 800;
                
            }else if($k>=2 && $k<=5){ //第三名-第六名
                $insertData[$k]['bonus'] = 1000;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 1000 : 500;
                
            }else{  //第七名-第十名
                $insertData[$k]['bonus'] = 600;
                $insertData[$k]['actual_bonus'] = $v->total_final_point > 0 ? 600 : 300;
                
            } 
           
            if($v->ordernum < 10){
                $insertData[$k]['desc'] = '策略数量不符';
                $insertData[$k]['status'] = 1;
                $insertData[$k]['actual_bonus'] = 0;
            }else if($v->week_final_point < 100){
                $insertData[$k]['desc'] = '周盈利点位不符';
                $insertData[$k]['status'] = 1;
                $insertData[$k]['actual_bonus'] = 0;
            }else{
                $insertData[$k]['desc'] = '';
                $insertData[$k]['status'] = 2;
            }
            
            $insertData[$k]['allpoint'] = round($v->total_final_point,2);
            $insertData[$k]['ranking'] = $k+1;
            $insertData[$k]['week_time'] = time();
            $insertData[$k]['week_profit'] = round($dataarr[$k]->week_final_point,2);
            $insertData[$k]['userid'] = $dataarr[$k]->id;
            $insertData[$k]['draw_status'] = 1;
            
            $id = DB::table('waihui_active_ranking')
                  ->insertGetId($insertData[$k]);  
            
        }

        if($id){
            echo '入库成功,最后id为：'.$id;
            return;
        }else{
            echo '入库失败';
            return false;
        }
    }
    //散点图
    public function sandian(Request $request){
        $userid =  trim($request->userid);
        $tel    = DB::table('waihui_member')->where(array('id'=>$userid))->value('tel');
        $time   = '';
        $end_point_str    = '';
        $profit_point_str = '';
        $loss_point_str   = '';
        $whe['o.tel'] = $tel;
        $whe['o.isstop'] = 0;
        $whe['o.ispersonal'] = 0;
//        $daysarr = DB::table('waihui_order as o')->select(DB::raw("FROM_UNIXTIME(o.end_time, '%Y年%m月%d日') AS days"))->where($whe)->groupBy('days')->orderBy('days','desc')->limit(7)->pluck('days');
//        DB::connection()->enableQueryLog();
        $result  = DB::table('waihui_order as o')->select('tradeid','begin_point','end_point','profit_point','loss_point','target_profit_point','target_loss_point','final_point',"begin_time","end_time",DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d日') as datetime"))->where($whe)->orderBy('o.end_time','desc')->limit(30)->get()->toArray();
//        ->whereIn(DB::raw("FROM_UNIXTIME(end_time, '%Y年%m月%d日')"),$daysarr)
//        $sql =DB::getQueryLog();
//        dd($sql);
//        dd($result);
        $result = array_reverse($result);
        foreach ($result as $k=>$v){
            $str = '';
            if($k < count($result)-1){
                $str = ',';
            }
            $time .= date('Y-m-d',$v->end_time).$str;
            $end_point_str .= $v->final_point.$str;
            $profit_point_str .= $v->profit_point.$str;
            $loss_point_str .= '-'.$v->loss_point.$str;
        }
        return view('sandiantu',compact('time','end_point_str','profit_point_str','loss_point_str'));
    }

    //时间分布散点图
    public function sandianTime(Request $request){
        $userid =  trim($request->userid);
        $tel    = DB::table('waihui_member')->where(array('id'=>$userid))->value('tel');
        $time_str = '';
        $whe['o.tel'] = $tel;
        $whe['o.isstop'] = 0;
        $whe['o.ispersonal'] = 0;
        $daysarr = DB::table('waihui_order as o')->select(DB::raw("FROM_UNIXTIME(o.end_time, '%Y年%m月%d日') AS days"))->where($whe)->groupBy('days')->orderBy('days','desc')->limit(30)->pluck('days');
//        DB::connection()->enableQueryLog();
        $result  = DB::table('waihui_order as o')->select('tradeid','begin_point','end_point','profit_point','loss_point','target_profit_point','target_loss_point','final_point',"begin_time","end_time",DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d日') as datetime"))->where($whe)->whereIn(DB::raw("FROM_UNIXTIME(end_time, '%Y年%m月%d日')"),$daysarr)->orderBy('o.begin_time','desc')->get()->toArray();
//        $sql =DB::getQueryLog();
//        dd($sql);
//        dd($result);

        foreach ($result as $k=>$v){
//            $time = round(($v->end_time - $v->begin_time)/3600,0);
            $time = date('Y-m-d',$v->begin_time);
            $time_str .= $time.','.date('H',$v->begin_time).';';
        }
//        dd($time_str);
        return view('sandiantimetu',compact('time_str'));
    }

    //总赢
    public function allPoint(Request $request){
        $where['isanalyst']     = '1';
        $where['o.ispersonal']  = 0; //网站下单的
        $where['o.isstop']      = 0; //已平仓的
        $tellist = DB::table('waihui_member as m')
                        ->join('waihui_order as o','m.tel','=','o.tel')
                        ->select('m.tel')
                        ->where($where)
                        ->whereBetween('o.end_time', [0, strtotime('now')])
                        ->havingRaw('SUM(o.final_point) > 0')
                        ->havingRaw('COUNT(o.id) > 10')
                        ->groupBy('m.tel')
                        ->pluck('m.tel');
        $result = DB::table('waihui_order')->select("final_point","end_time",DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d') as datetime"))->where([['final_point','!=' ,null]])->whereIn('tel',$tellist)->orderBy('datetime','asc')->get()->toArray();
//        dd($result);
        $str       = '';
        if($result){
            $total     = 0;
            $timeDay   = [];    //时间
            $pointarr  = [];   //存放 每天 最高、最低、开始、结束
            $daypoint  = [];  //当天数据
            $prepoint  = [];   //存放昨天的数据
            $i         = 0;    //每天的单量
            $num       = 0;    //总单量
            foreach($result as $k=>$v){
                if($k <= count($result)-1){
                    $total = $total + $result[$k]->final_point; //每天每单相加后的值
                    $daypoint[] = $total; //将值放入数组中 以便获取 最大值最小值
                    $i ++ ; //每天的单量
                    //条件是否正确
                    if($k == count($result)-1){ //最后一天数据
                        $istrue = true;
                    }else{
                        $istrue = $result[$k]->datetime != $result[$k+1]->datetime ?true:false; //当前日期不等于下一个日期，则当前日期结束
                    }
                    if($istrue){ //当前一天的结束
                        $str .= $result[$k]->datetime.','; //拼接时间
//                        $pointarr[$result[$k]->datetime] = [];

                        //第一天和以后每天的区别
                        if($timeDay){
//                            array_push($pointarr[$result[$k]->datetime],$prepoint[count($prepoint)-1]); //开始值为前一天的结束值
                            $str .= $prepoint[count($prepoint)-1].','.$daypoint[count($daypoint)-1].','; //拼接开始值、结束值
                        }else{
//                            array_push($pointarr[$result[$k]->datetime],0); //第一天开始值 为0
                            $str .= '0,'.$daypoint[count($daypoint)-1].','; //拼接开始值、结束值
                        }
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[count($daypoint)-1]); //结束值
                        //单均盈利
                        $num += $i;
                        $singlepoint = round($daypoint[count($daypoint)-1]/$num,2);

                        $prepoint  = $daypoint; //将数据存起来

                        sort($daypoint); //对数组进行从小到大排序
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[0]); //一天中最小值
//                        array_push($pointarr[$result[$k]->datetime],$daypoint[count($daypoint)-1]); //一天中最大值
//                        array_push($pointarr[$result[$k]->datetime],$i); //单量

                        $str .= $daypoint[0].','.$daypoint[count($daypoint)-1].','.$i.",0"; //拼接最小值、最大值、单量
                        $str .= ",".$singlepoint.";";

//                        array_push($pointarr[$result[$k]->datetime],$singlepoint); //单均盈利

                        $timeDay[] = $result[$k]->datetime; //时间数组
                        $daypoint  = []; //新的一天重置数组
                        $i         = 0;
                    }
                }
            }
        }
        return view('point',compact('str'));
    }
}
